package com.platform.utils;


import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class ThreadLocalUtil {

    /**
     * 租户IDkey
     */
    public final static String TENANT_ID_KEY = "tenant_id_key";

    /**
     * 默认数据源
     */
    public final static String DEFAULT_TENANT_ID = "my-platform";

    private static final ThreadLocal<HashMap<String, Object>> THREAD_LOCAL_DATA = new ThreadLocal<HashMap<String, Object>>() {

        @Override
        protected HashMap<String, Object> initialValue() {
            return new HashMap<>(10);
        }

    };


    /**
     * 获取缓存数据
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T get(String key) {
        return (T) THREAD_LOCAL_DATA.get().get(key);
    }

    /**
     * 获取带默认值
     *
     * @param key
     * @param defaultValue
     * @param <T>
     * @return
     */
    public static <T> T get(String key, T defaultValue) {
        T v = get(key);

        return v == null ? defaultValue : v;
    }

    /**
     * 设置缓存数据
     *
     * @param key
     * @param data
     * @param <T>
     */
    public static <T> void set(String key, T data) {
        THREAD_LOCAL_DATA.get().put(key, data);
    }
}
